﻿using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ServiceDemo
{
    [Activity(Label = "ServiceDemo", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        bool isBound = false;
        bool isConfigurationChange = false;
        TestServiceBinder binder;
        TestServiceConnection testServiceConnection;

        private MyBroadcastReceive receive = null;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var btnStartService = FindViewById<Button>(Resource.Id.btnStartService);
            btnStartService.Click += delegate
            {
                var demoServiceIntent = new Intent("ServiceDemo");
                testServiceConnection = new TestServiceConnection(this);
                ApplicationContext.BindService(demoServiceIntent, testServiceConnection, Bind.AutoCreate);

                StartService(new Intent("ServiceDemo"));

                Toast.MakeText(this, "Service Started", ToastLength.Short).Show();
            };

            var btnStopService = FindViewById<Button>(Resource.Id.btnStopService);
            btnStopService.Click += delegate
            {
                if (!isConfigurationChange)
                {
                    if (isBound)
                    {
                        ApplicationContext.UnbindService(testServiceConnection);
                        isBound = false;
                    }
                }

                StopService(new Intent("ServiceDemo"));

                Toast.MakeText(this, "Service Stopped", ToastLength.Short).Show();
            };

            var btndoSomething = FindViewById<Button>(Resource.Id.btndoSomething);
            btndoSomething.Click += delegate
            {
                if (isBound)
                {
                    RunOnUiThread(() =>
                    {
                        string text = binder.GetDemoService().DoSomething();
                        Toast.MakeText(this, text, ToastLength.Short).Show();
                    }
                    );
                }
            };

            var btnStartTimer = FindViewById<Button>(Resource.Id.btnStartTimer);
            btnStartTimer.Click += delegate
            {
                if (isBound)
                    RunOnUiThread(() => binder.GetDemoService().ProcessStart());
            };

            var btnStopTimer = FindViewById<Button>(Resource.Id.btnStopTimer);
            btnStopTimer.Click += delegate
            {
                if (isBound)
                    RunOnUiThread(() => binder.GetDemoService().ProcessStop());
            };

            testServiceConnection = LastNonConfigurationInstance as TestServiceConnection;

            if (testServiceConnection != null)
                binder = testServiceConnection.Binder;

            var intentFilter = new IntentFilter();

            //为BroadcastReceiver指定action，即要监听的消息名字。
            intentFilter.AddAction(Constants.MessageCode);

            receive = new MyBroadcastReceive();
            //注册监听
            RegisterReceiver(receive, intentFilter);
        }

        protected override void OnStart()
        {
            base.OnStart();
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            //取消监听
            UnregisterReceiver(receive);
            if (!isConfigurationChange)
            {
                if (isBound)
                {
                    UnbindService(testServiceConnection);
                    isBound = false;
                }
            }
        }

        // return the service connection if there is a configuration change
        public override Java.Lang.Object OnRetainNonConfigurationInstance()
        {
            base.OnRetainNonConfigurationInstance();

            isConfigurationChange = true;

            return testServiceConnection;
        }

        private class MyBroadcastReceive : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
                if (Constants.MessageCode == intent.Action)
                {
                    var result = intent.Extras.GetString(Constants.Key);
                    Toast.MakeText(context, result, ToastLength.Long).Show();
                }
            }
        }

        class TestServiceConnection : Java.Lang.Object, IServiceConnection
        {
            MainActivity activity;
            TestServiceBinder binder;

            public TestServiceBinder Binder
            {
                get
                {
                    return binder;
                }
            }

            public TestServiceConnection(MainActivity activity)
            {
                this.activity = activity;
            }

            public void OnServiceConnected(ComponentName name, IBinder service)
            {
                var binder = service as TestServiceBinder;

                if (binder != null)
                {
                    activity.binder = binder;
                    activity.isBound = true;
                    // keep instance for preservation across configuration changes
                    this.binder = binder;
                }
            }

            public void OnServiceDisconnected(ComponentName name)
            {
                activity.isBound = false;
            }
        }
    }
}

